import { act } from "react-dom/cjs/react-dom-test-utils.production.min";

//resux  定义 状态
const initialState={
   cartList:JSON.parse(localStorage.getItem("cart"))|| [],
   totalCont:0,
   allSelect:false
}

export function cartReducer(state=initialState,action){
    switch (action.type){
        case "ADDCART":
            //去重
            var flag=false;//默认购物车中没有这个商品
            state.cartList.forEach((element)=>{
                if(element._id==action.item._id){
                    flag=true;
                    element.count+=1;

                }
            })

            if(!flag){
                action.item.count=1
                action.item.checked=false
                state.cartList.push(action.item)
            }


            localStorage.setItem("cart",JSON.stringify(state.cartList));
            return {
             cartList:state.cartList,
             totalCont:state.totalCont,
             allSelect:state.allSelect
            };
            case "CHANKEITEMSTATUS":
                //找到将要修改状态的商品
                state.cartList.forEach((element)=>{
                    if(element._id=action.item._id){
                        element.checked=action.item.checked
                    }
                })
                //同步全选状态
                //数组中所有元素 都必须马满足条件 ，every返回true  否则返回false
                state.cartList.every((element)=>{
                    return element.checked=true;

                })

                // state.allSelect
                //计算总计和总量
                state.totalCont=0;
                state.cartList.forEach((element)=>{
                    if(element.checked){
                        state.totalCont+=element.count
                    }
                })



                return {
                    cartList:state.cartList,
                    totalCont:state.totalCont,
                    allSelect:state.allSelect
                }


                case "ALLSELECT":
                    state.allSelect=action.bollean
                    //同步没哟个商品的选中状态
                    state.cartList.forEach((element)=>{
                        element.checked=action.bollean
                    })

                     //计算总计和总量
                state.totalCont=0;
                state.cartList.forEach((element)=>{
                    if(element.checked){
                        state.totalCont+=element.count
                    }
                })




                    return {
                        cartList:state.cartList,
                        totalCont:state.totalCont,
                        allSelect:state.allSelect
                    }




        default:
            return state
    }
   
}